<template>
  <div class="ticket-container">
    <div class="header">
      <div class="left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索工单"
          prefix-icon="Search"
          clearable
          class="search-input"
        />
        <el-select v-model="typeFilter" placeholder="工单类型" clearable>
          <el-option label="问题反馈" value="feedback" />
          <el-option label="功能建议" value="suggestion" />
          <el-option label="故障报修" value="repair" />
        </el-select>
        <el-select v-model="statusFilter" placeholder="状态" clearable>
          <el-option label="待处理" value="pending" />
          <el-option label="处理中" value="processing" />
          <el-option label="已完成" value="completed" />
        </el-select>
        <el-select v-model="priorityFilter" placeholder="优先级" clearable>
          <el-option label="低" value="low" />
          <el-option label="中" value="medium" />
          <el-option label="高" value="high" />
        </el-select>
      </div>
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>创建工单
      </el-button>
    </div>

    <el-table
      :data="ticketList"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="工单号" width="100" />
      <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
      <el-table-column prop="type" label="类型" width="100">
        <template #default="{ row }">
          <el-tag>{{ row.type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="100">
        <template #default="{ row }">
          <el-tag :type="getPriorityType(row.priority)">
            {{ row.priority }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="创建人" width="120" />
      <el-table-column prop="handler" label="处理人" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleView(row)">
            查看
          </el-button>
          <el-button 
            type="success" 
            link 
            v-if="row.status !== 'completed'"
            @click="handleProcess(row)"
          >
            处理
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 工单表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '创建工单' : '处理工单'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="ticketForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title" v-if="dialogType === 'create'">
          <el-input v-model="ticketForm.title" placeholder="请输入工单标题" />
        </el-form-item>
        <el-form-item label="类型" prop="type" v-if="dialogType === 'create'">
          <el-select v-model="ticketForm.type" placeholder="请选择工单类型">
            <el-option label="问题反馈" value="feedback" />
            <el-option label="功能建议" value="suggestion" />
            <el-option label="故障报修" value="repair" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority" v-if="dialogType === 'create'">
          <el-select v-model="ticketForm.priority" placeholder="请选择优先级">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
          </el-select>
        </el-form-item>
        <el-form-item 
          :label="dialogType === 'create' ? '描述' : '处理说明'" 
          prop="content"
        >
          <el-input
            v-model="ticketForm.content"
            type="textarea"
            :rows="4"
            :placeholder="dialogType === 'create' ? '请输入工单描述' : '请输入处理说明'"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <el-button class="ml-3" @click="handleUpload">
              上传到服务器
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png/pdf文件，且不超过10mb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 工单详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="工单详情"
      width="800px"
    >
      <div class="ticket-detail">
        <div class="basic-info">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="工单号">
              {{ currentTicket?.id }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(currentTicket?.status)">
                {{ currentTicket?.status }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="类型">
              <el-tag>{{ currentTicket?.type }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="优先级">
              <el-tag :type="getPriorityType(currentTicket?.priority)">
                {{ currentTicket?.priority }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建人">
              {{ currentTicket?.creator }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ currentTicket?.createTime }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="ticket-content">
          <h3>工单内容</h3>
          <div class="content-text">{{ currentTicket?.content }}</div>
        </div>
        <div class="process-history">
          <h3>处理记录</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in currentTicket?.activities"
              :key="index"
              :timestamp="activity.time"
              :type="activity.type"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'

const loading = ref(false)
const searchQuery = ref('')
const typeFilter = ref('')
const statusFilter = ref('')
const priorityFilter = ref('')
const dialogVisible = ref(false)
const detailVisible = ref(false)
const dialogType = ref<'create' | 'process'>('create')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
const formRef = ref<FormInstance>()
const currentTicket = ref<any>(null)

// 表单数据
const ticketForm = ref({
  title: '',
  type: '',
  priority: '',
  content: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入工单标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择工单类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ]
}

// 模拟工单数据
const ticketList = [
  {
    id: 'T2023001',
    title: '系统登录异常',
    type: '问题反馈',
    priority: '高',
    status: '处理中',
    creator: '张三',
    handler: '李四',
    createTime: '2023-12-01 12:00:00',
    content: '用户反馈无法正常登录系统',
    activities: [
      {
        type: 'primary',
        content: '创建工单',
        time: '2023-12-01 12:00:00'
      },
      {
        type: 'success',
        content: '开始处理',
        time: '2023-12-01 14:00:00'
      }
    ]
  },
  {
    id: 'T2023002',
    title: '建议增加导出功能',
    type: '功能建议',
    priority: '中',
    status: '待处理',
    creator: '王五',
    handler: '-',
    createTime: '2023-12-01 13:00:00',
    content: '建议在用户列表增加导出Excel功能',
    activities: [
      {
        type: 'primary',
        content: '创建工单',
        time: '2023-12-01 13:00:00'
      }
    ]
  }
]

// 获取优先级类型
const getPriorityType = (priority: string) => {
  const types: Record<string, string> = {
    '高': 'danger',
    '中': 'warning',
    '低': 'info'
  }
  return types[priority] || 'info'
}

// 获取状态类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    '待处理': 'info',
    '处理中': 'warning',
    '已完成': 'success'
  }
  return types[status] || 'info'
}

// 处理创建工单
const handleCreate = () => {
  dialogType.value = 'create'
  dialogVisible.value = true
  ticketForm.value = {
    title: '',
    type: '',
    priority: '',
    content: ''
  }
}

// 处理查看工单
const handleView = (row: any) => {
  currentTicket.value = row
  detailVisible.value = true
}

// 处理工单
const handleProcess = (row: any) => {
  dialogType.value = 'process'
  dialogVisible.value = true
  ticketForm.value = {
    title: row.title,
    type: row.type,
    priority: row.priority,
    content: ''
  }
}

// 处理删除工单
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除工单 ${row.id} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功')
  })
}

// 处理文件变更
const handleFileChange = (file: any) => {
  console.log('选择文件：', file)
}

// 处理文件上传
const handleUpload = () => {
  ElMessage.success('文件上传成功')
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success(dialogType.value === 'create' ? '创建成功' : '处理成功')
      dialogVisible.value = false
    }
  })
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}
</script>

<style lang="scss" scoped>
.ticket-container {
  padding: var(--spacing-base);

  .header {
    display: flex;
    justify-content: space-between;
    margin-bottom: var(--spacing-large);

    .left {
      display: flex;
      gap: var(--spacing-base);

      .search-input {
        width: 200px;
      }
    }
  }

  .pagination {
    margin-top: var(--spacing-large);
    display: flex;
    justify-content: flex-end;
  }
}

.ticket-detail {
  .basic-info,
  .ticket-content,
  .process-history {
    margin-bottom: var(--spacing-large);

    h3 {
      margin-bottom: var(--spacing-base);
      font-size: 16px;
      font-weight: 500;
    }
  }

  .content-text {
    padding: var(--spacing-base);
    background: var(--bg-color);
    border-radius: var(--radius-base);
    min-height: 100px;
  }
}

.ml-3 {
  margin-left: 12px;
}
</style> 